<template>
  <div>
    <div style="margin-bottom:20px;">
      选择校区:
      <a-select
        style="width: 150px"
        v-model="dataSourse.structures_id"
        :disabled="status"
        @change="changeSchool"
        placeholder="请先选择校区"
      >
        <a-select-option
          v-for="(item,index) in schoolSelect"
          :key="index"
          :value="item.id"
        >{{item.name}}</a-select-option>
      </a-select>
      <span v-if="dataSourse.structures_id">
        <a-button
          type="primary"
          style="margin:0  20px 20px 20px"
          @click="showChild('courseComponents')"
        >选择课程</a-button>
        <a-button
          type="primary"
          style="margin:0  20px 20px 0"
          @click="showChild('itemComponents')"
        >选择物品</a-button>
        <a-button type="primary" style="margin:0  20px 20px 0" @click="showChild('cost')">选择费用</a-button>
      </span>
    </div>

    <div class="tables">
      <div class="tablesTitle" style="margin-bottom:20px;">购买信息</div>
      <a-table
        :columns="columns"
        :dataSource="data"
        style="border:1px solid #e8e8e8;"
        :pagination="false"
      >
        <!-- :scroll="{ x: 1800 }" -->
        <span slot="name" slot-scope="text,record,index">
          <!-- <a-input v-model="record.name"></a-input> -->
          <a-select
            size="small"
            v-model="record.course_type"
            class="courseTypeSelectApply"
            v-if="record.project_type==1"
            style="width: 60px;font-size:10px;"
            @change="changeCourseType(record,index)"
          >
            <a-select-option :value="0">购买</a-select-option>
            <a-select-option :value="1">新报</a-select-option>
            <a-select-option :value="2">续报</a-select-option>
            <a-select-option :value="3">扩科</a-select-option>
          </a-select>
          <span
            style="display:inline-block;width:150px;padding-left:14px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;line-height:12px;"
          >{{record.name}}</span>
          <span>
            <a-icon type="delete" theme="filled" style="margin-left:10px;" @click="delLine(index)" />
          </span>
          <p style="margin-top:10px;" v-if="record.project_type==1&&record.course_type_num==2">
            选择班级：
            <a-select
              v-model="record.class_id"
              style="width:140px;"
              @change="changeCourseType(record,index)"
            >
              <a-select-option
                v-for="(item,index) in record.class"
                :key="index"
                :value="item.id"
              >{{item.name}}</a-select-option>
            </a-select>
          </p>
        </span>
        <!-- 定价标准 -->
        <span slot="price_rule" slot-scope="text,record,index">
          <span v-if="record.project_type==1">
            <a-select
              v-model="record.price_type"
              style="width: 120px"
              v-if="record.price.length>0"
              @change="change(record,index)"
            >
              <a-select-option
                v-for="(item,index) in record.price"
                :key="index"
                :value="item.id"
              >{{item.unit_price}}元/{{item.type==1?'课时':item.type==2?'天':''}}</a-select-option>
            </a-select>
          </span>
          <span v-else>￥{{record.unit_price}}/件</span>
        </span>
        <!-- 单价 -->
        <!-- <span slot="singlePrice" slot-scope="text,record,index">
          <a-input-number
            id="inputNumber"
            :min="0"
            :step="0.01"
            v-model="record.unit_price"
            @change="changeUnit_price(record,index)"
          />
          元/{{record.choiceCombo.type==1?'课时':record.choiceCombo.type==2?'月':''}}
        </span>-->
        <!-- 购买数量 -->
        <span slot="buyNumber" slot-scope="text,record,index">
          <a-input-number
            :min="0"
            v-model="record.buy_number"
            @change="changeTotalNum(record,index)"
          />
        </span>
        <!-- 原价 -->
        <!-- <span
          slot="originalPrice"
          slot-scope="text,record,index"
        >￥{{record.choiceCombo.unit_price||'0'}}</span>-->
        <!-- 赠送数量 -->
        <span slot="give_num" slot-scope="text,record,index">
          <a-input-number
            :min="0"
            v-model="record.give_number"
            @change="changeTotalNum(record,index)"
          />
        </span>
        <!-- 优惠折扣 -->
        <span slot="disCount" slot-scope="text,record,index">
          <a-input
            :style="{width: 'calc(100%)'}"
            v-model="record.discount.value"
            @change="changeDiscount(record,index)"
          >
            <a-select
              slot="addonBefore"
              v-model="record.discount.type"
              style="width: 80px"
              :defaultValue="1"
              @change="changeDiscount(record,index)"
            >
              <a-select-option :value="1">直减</a-select-option>
              <a-select-option :value="2">折扣</a-select-option>
            </a-select>
          </a-input>
        </span>
        <!-- 签约数量 -->
        <span slot="total_number" slot-scope="text,record,index">
          <span v-if="record.project_type==1">
            <span v-if="record.choiceCombo.type==2">
              <span style="display:inline-block;width:300px;text-align:left;padding-left:16px;">
                开始日期：
                <a-date-picker v-model="record.buy_start_time" @change="changeDate(record,index)" />
              </span>
              <br />
              <span
                style="display:inline-block;width:300px;text-align:left;padding-left:16px;margin-top:10px;"
              >结束日期：&nbsp;&nbsp;&nbsp;{{record.buy_end_time||'--'}} (共{{record.buy_number+record.give_number}}天)</span>
            </span>
            <span v-else>
              <span>{{record.total_number||'0'}}课时</span>
            </span>
          </span>
          <span v-else>{{record.total_number||'0'}}件</span>
        </span>
        <!-- 签约金额 -->
        <span slot slot-scope="text,record">￥{{record.signing_price||'0'}}</span>
      </a-table>
    </div>
    <course-model ref="course" @receive="courseData"></course-model>
    <item-model ref="item" @receive="itemData"></item-model>
    <cost-model ref="cost" @receive="costData"></cost-model>
    <div style="margin-top:20px;text-align:right;">
      <a-button type="primary" @click="nextStep">下一步</a-button>
      <a-button style="margin-left: 8px" @click="prevStep" v-if="!dataSourse.student_id">上一步</a-button>
    </div>
  </div>
</template>

<script>
import courseModel from '@/components/course'
import itemModel from '@/components/item'
import moment from 'moment'
import { campusList } from '@/api/structure'
import costModel from '@/components/cost'
export default {
  name: 'Step2',
  components: {
    courseModel,
    itemModel,
    costModel
  },
  props: ['dataSourse'],
  data() {
    return {
      status: false, //判断校区是否可以更换
      labelCol: { lg: { span: 5 }, sm: { span: 5 } },
      wrapperCol: { lg: { span: 19 }, sm: { span: 19 } },
      loading: false,
      timer: 0,
      columns: [
        {
          title: '名称',
          dataIndex: 'name',
          fixed: 'left',
          width: 300,
          ellipsis: true,
          align: 'left',
          scopedSlots: { customRender: 'name' }
        },

        {
          title: '定价标准',
          dataIndex: 'price',
          ellipsis: true,
          scopedSlots: { customRender: 'price_rule' }
        },
        // {
        //   title: '单价',
        //   dataIndex: 'singlePrice',
        //   ellipsis: true,
        //   scopedSlots: { customRender: 'singlePrice' }
        // },
        {
          title: '购买数量',
          dataIndex: 'buy_number',
          scopedSlots: { customRender: 'buyNumber' }
        },
        // {
        //   title: '原价',
        //   dataIndex: 'originalPrice',
        //   ellipsis: true,
        //   align: 'center',
        //   scopedSlots: { customRender: 'originalPrice' }
        // },
        {
          title: '赠送数量',
          dataIndex: 'give_num',
          ellipsis: true,
          scopedSlots: { customRender: 'give_num' }
        },
        {
          title: '优惠/折扣',
          dataIndex: 'disCount',
          ellipsis: true,
          width: 200,
          scopedSlots: { customRender: 'disCount' }
        },
        {
          title: '签约数量/签约时长',
          dataIndex: 'total_number',
          align: 'center',
          width: 310,
          scopedSlots: { customRender: 'total_number' }
        },
        {
          title: '签约金额',
          dataIndex: 'signing_price',
          fixed: 'right',
          align: 'center',
          scopedSlots: { customRender: 'signing_price' }
        }
      ],
      data: [],
      courseSelectRows: [],
      schoolSelect: [] //校区列表
    }
  },
  created() {
    campusList({ school_id: this.$store.state.user.school }).then(res => {
      this.schoolSelect = res
    })
    if (this.dataSourse.content_arr) {
      this.data = JSON.parse(JSON.stringify(this.dataSourse.content_arr))
      this.$forceUpdate()
    }
    if (!this.dataSourse.structures_id) {
      this.dataSourse.structures_id = undefined
    }
  },
  methods: {
    nextStep() {
      if (this.dataSourse.structures_id) {
        this.$emit('nextStep', this.data)
      } else {
        this.$message.error('请选择校区')
        return
      }
    },
    prevStep() {
      let obj = JSON.parse(JSON.stringify(this.dataSourse))
      obj.content_arr = this.data
      this.$emit('prevStep', obj)
    },
    showChild(e) {
      if (e == 'courseComponents') {
        this.$refs.course.showModal(this.courseSelectRows, this.dataSourse.structures_id)
      } else if (e == 'itemComponents') {
        this.$refs.item.showModal()
      } else if (e == 'cost') {
        this.$refs.cost.showModal()
      }
    },
    courseData(data) {
      let arr = []
      this.data.forEach(item => {
        arr.push(item.id)
      })
      let e = JSON.parse(JSON.stringify(data))
      if (e.length > 0) {
        this.status = true
      }
      e.forEach((val, index) => {
        if (val.price.length > 0) {
          val.project_id = val.id
          val.project_type = 1 //类型：1课程，2物品，3费用
          val.course_type_num = e.type  //一对一或一对多  1——>对一 2——>对多
          val.price_type = val.price[0].id //当前选择的定价标准ID
          val.choiceCombo = val.price[0] //当前选择的定价标准 对象
          val.unit_price = val.price[0].unit_price //当前单价
          if (val.class.length > 0) {
            val.class_id = val.class[0].id
          } else {
            val.class_id = null
          }
          val.buy_number = 0 //购买数量
          val.give_number = 0 //赠送数量
          val.signing_price = 0 //总价
          val.course_type = 0 //表明当前选择课程类型 课程类型：0购买，1新报，2续报，3扩科
          val.buy_start_time = null
          val.discount = {
            //优惠方式  type：1直减 2折扣
            type: 1,
            value: 0
          }
        } else {
          val.project_id = val.id
          val.project_type = 1 //类型：1课程，2物品，3费用
          val.course_type_num = e.type  //一对一或一对多  1——>一对一 2——>一对多
          val.price_type = null //当前选择的定价标准ID
          val.unit_price = null //当前单价
          if (val.class.length > 0) {
            val.class_id = val.class[0].id
          } else {
            val.class_id = null
          }
          val.buy_number = 0 //购买数量
          val.give_number = 0 //赠送数量
          val.signing_price = 0 //总价
          val.course_type = 0 //表明当前选择课程类型 课程类型：0购买，1新报，2续报，3扩科
          val.discount = {
            //优惠方式  type：1直减 2折扣
            type: 1,
            value: 0
          }
        }
        if (arr.indexOf(val.id) == -1) {
          this.data.push(val)
        }
      })
    },
    itemData(e) {
      e.forEach(val => {
        val.project_id = val.id
        val.project_type = 2
        val.buy_number = 0 //购买数量
        val.give_number = 0 //赠送数量
        val.signing_price = 0 //总价
        val.discount = {
          //优惠方式  type：1直减 2折扣
          type: 1,
          value: 0
        }
        this.data.push(val)
      })
    },
    costData(e) {
      e.forEach(val => {
        val.project_id = val.id
        val.project_type = 3
        val.buy_number = 0 //购买数量
        val.give_number = 0 //赠送数量
        val.signing_price = 0 //总价
        val.discount = {
          //优惠方式  type：1直减 2折扣
          type: 1,
          value: 0
        }
        this.data.push(val)
      })
    },
    delLine(index) {
      this.data.splice(index, 1)
      let arr = []
      this.data.forEach(val => {
        if (val.type == 1) {
          arr.push(1)
        }
      })
      if (arr.length > 0) {
        this.status = true
      } else {
        this.status = false
      }
    },
    //购买类型
    changeCourseType(e, index) {
      this.data.splice(index, 1, e)
    },
    //定价标准切换
    change(e, index) {
      e.price.forEach(val => {
        if (val.id == e.price_type) {
          e.choiceCombo = val
          e.unit_price = val.unit_price
          this.data.splice(index, 1, e)
        }
      })
    },
    // 购买数量/赠送数量切换
    changeTotalNum(e, index) {
      e.total_number = e.buy_number + e.give_number
      let benefit = e.discount.value
      if (e.buy_number > 0) {
        if (e.discount.type == 1 && benefit >= 0) {
          //直减  计算总价
          if (benefit < e.buy_number * e.unit_price) {
            e.signing_price = (e.buy_number * e.unit_price - e.discount.value).toFixed(2)
          } else {
            e.signing_price = 0
          }
        } else if (e.discount.type == 2 && benefit > 0) {
          e.signing_price = (e.unit_price * e.buy_number * e.discount.value).toFixed(2)
        } else if (e.discount.type == 2 && benefit == 0) {
          e.signing_price = (e.unit_price * e.buy_number).toFixed(2)
        }
      } else {
        e.signing_price = 0
      }
      this.changeDate(e, index)
      this.data.splice(index, 1, e)
    },
    // 优惠类型切换
    changeDiscount(e, index) {
      let re = /^\d+(?=\.{0,1}\d+$|$)/
      if (e.discount.value != 0) {
        if (!re.test(e.discount.value)) {
          e.discount.value = 0
        }
      }
      if (e.discount.type == 1) {
        //直减计算总价
        if (e.unit_price * e.buy_number - e.discount.value > 0) {
          e.signing_price = (e.buy_number * e.unit_price - e.discount.value).toFixed(2)
        } else {
          e.signing_price = 0
        }
      }
      if (e.discount.type == 2) {
        //折扣计算总价
        if (e.discount.value > 0) {
          e.signing_price = (e.unit_price * e.buy_number * e.discount.value).toFixed(2)
        }
      }
      this.data.splice(index, 1, e)
    },
    // 切换开始时间
    changeDate(e, index) {
      let start = new Date(moment(e.buy_start_time).format('YYYY-MM-DD'))
      let end = new Date(moment(e.buy_start_time).format('YYYY-MM-DD'))
      end.setDate(start.getDate() + e.total_number)
      if (e.total_number > 0 && e.buy_start_time) {
        let endTime = new Date(end)
        e.buy_end_time = endTime.getFullYear() + '-' + (endTime.getMonth() + 1) + '-' + endTime.getDate() || null
      }
      this.data.splice(index, 1, e)
    },
    changeSchool(e) {
      this.dataSourse.structures_id = e
      this.$forceUpdate()
    }
  },
  beforeDestroy() {
    clearTimeout(this.timer)
  }
}
</script>
<style lang="less">
@import '~@/components/index.less';
.courseTypeSelectApply {
  height: 24px;
  .ant-select-selection {
    line-height: 24px;
    height: 24px;
    border: 1px solid @primary-color;
    color: @primary-color;
    .ant-select-selection__rendered {
      line-height: 24px;
    }
    .ant-select-arrow {
      color: @primary-color;
    }
  }
}
</style>
<style lang="less" scoped>
.stepFormText {
  margin-bottom: 24px;

  .ant-form-item-label,
  .ant-form-item-control {
    line-height: 22px;
  }
}
</style>
